import { routerRedux } from 'dva/router';
import { stringify } from 'qs';
// import { fakeAccountLogin, getFakeCaptcha } from '@/services/api';
import * as userService from '../services/user';
import { login } from '@/services/user';
import { setAuthority } from '@/utils/authority';
import { getPageQuery } from '@/utils/utils';
import { reloadAuthorized } from '@/utils/Authorized';
import { notification } from 'antd';


export default {
  namespace: 'login',
  state: {
    status: undefined,
  },
  effects: {
    * login({ payload }, { call, put }) {
      const data = yield call(userService.login, payload);
      if (data.code == 'SUCCESS') {
        yield put({
          type: 'changeLoginStatus',
          payload: {
            status: 200,
            // currentAuthority: data.userInfo.role,
            // currentToken: data.token,
          },
        });
        /*reloadAuthorized();
        const urlParams = new URL(window.location.href);
        const params = getPageQuery();
        let {redirect} = params;
        if (redirect) {
          const redirectUrlParams = new URL(redirect);
          if (redirectUrlParams.origin === urlParams.origin) {
            redirect = redirect.substr(urlParams.origin.length);
            if (redirect.startsWith('/#')) {
              redirect = redirect.substr(2);
            }
          } else {
            window.location.href = redirect;
            return;
          }
        }*/
        yield put(routerRedux.replace({
          pathname: '/article/list',
        }));
      } else {
        yield put({
          type: 'setState',
          payload: {
            status: 'error',
          },
        });
      }
    },
    * getCaptcha({ payload }, { call }) {
      yield call(getFakeCaptcha, payload);
    },
    * logout(_, { put }) {
      yield put({
        type: 'changeLoginStatus',
        payload: {
          status: false,
        },
      });
      reloadAuthorized();
      yield put(
        routerRedux.push({
          pathname: '/user/login',
          search: stringify({
            redirect: window.location.href,
          }),
        }),
      );
    },
  },

  reducers: {
    changeLoginStatus(state, { payload }) {
      return {
        ...state,
        status: payload.status,
      };
    },
    setState(state, { payload: { status } }) {
      return {
        ...state,
        status: status,
      };
    },
  },
};
